<template>
  <view class="add-child-page">
    <form @submit="onSubmit">
      <!-- 所属家族 -->
      <view class="form-item">
        <text>所属家族</text>
        <picker :range="familyOptions" range-key="label" @change="onFamilyChange">
          <view class="picker">{{ getFamilyLabel(formData.familyId) || "请选择" }}</view>
        </picker>
      </view>
      <!-- 姓 -->
      <view class="form-item">
        <text class="required">姓</text>
        <input v-model="formData.firstName" placeholder="请输入姓" />
      </view>
      <!-- 名 -->
      <view class="form-item">
        <text class="required">名</text>
        <input v-model="formData.lastName" placeholder="请输入名" />
      </view>
      <!-- 昵称 -->
      <view class="form-item">
        <text>昵称</text>
        <input v-model="formData.nickname" placeholder="请输入昵称" />
      </view>
      <!-- 字辈 -->
      <view class="form-item">
        <text>字辈</text>
        <picker :range="zibeiOptions" range-key="label" @change="onZibeiChange">
          <view class="picker">{{ getZibeiLabel(formData.genation) || "请选择" }}</view>
        </picker>
      </view>
      <!-- 性别 -->
      <view class="form-item">
        <text class="required">性别</text>
        <picker :range="genderOptions" range-key="label" @change="onGenderChange">
          <view class="picker">{{ getGenderLabel(formData.gender) || "请选择" }}</view>
        </picker>
      </view>
      <!-- 是否在世 -->
      <view class="form-item">
        <text class="required">是否在世</text>
        <picker :range="aliveOptions" range-key="label" @change="onAliveChange">
          <view class="picker">{{ getAliveLabel(formData.alive) || "请选择" }}</view>
        </picker>
      </view>
      <!-- 头像照片 -->
      <view class="form-item">
        <text class="required">头像照片</text>
        <AvatarUploader v-model="formData.photoUrl" />
      </view>
      <!-- 职业 -->
      <view class="form-item">
        <text class="required">职业</text>
        <input v-model="formData.occupation" placeholder="请输入职业" />
      </view>
      <!-- 籍贯 -->
      <view class="form-item">
        <text class="required">籍贯</text>
        <input v-model="formData.birthPlace" placeholder="请输入籍贯" />
      </view>
      <!-- 地址 -->
      <view class="form-item">
        <text class="required">地址</text>
        <input v-model="formData.address" placeholder="请输入地址" />
      </view>
      <!-- 出生日期 -->
      <view class="form-item">
        <text class="required">出生日期</text>
        <view class="date-row">
          <picker :range="eraOptions" range-key="label" @change="onBirthEraChange">
            <view class="era-picker">{{ getBirthEraLabel(formData.birthEra) || "公元" }}</view>
          </picker>
          <picker mode="date" @change="onBirthDateChange">
            <view class="date-picker">{{ getDisplayBirthDate() || "请选择出生日期" }}</view>
          </picker>
        </view>
      </view>
      <!-- 死亡日期 -->
      <view class="form-item">
        <text>死亡日期</text>
        <view class="date-row">
          <picker :range="eraOptions" range-key="label" @change="onDeathEraChange">
            <view class="era-picker">{{ getDeathEraLabel(formData.deathEra) || "公元" }}</view>
          </picker>
          <picker mode="date" @change="onDeathDateChange">
            <view class="date-picker">{{ getDisplayDeathDate() || "请选择死亡日期" }}</view>
          </picker>
        </view>
      </view>
      <!-- 个人简介 -->
      <view class="form-item">
        <text>个人简介</text>
        <textarea v-model="formData.biography" placeholder="请输入个人简介" rows="3" />
      </view>
      <!-- 按钮 -->
      <view class="form-actions">
        <wd-button type="info" size="large" @click="onCancel">取消</wd-button>
        <wd-button type="primary" size="large" form-type="submit">确定</wd-button>
      </view>
    </form>
  </view>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import AvatarUploader from "@/components/AvatarUploader/AvatarUploader.vue";
import PersonAPI from "@/api/genealogy/person";
import FamilyAPI from "@/api/genealogy/family";

interface FormData {
  familyId: string;
  firstName: string;
  lastName: string;
  nickname: string;
  genation: string;
  gender: string;
  alive: string;
  photoUrl: string;
  occupation: string;
  birthPlace: string;
  address: string;
  birthDate: string;
  deathDate: string;
  birthEra: string;
  deathEra: string;
  biography: string;
  parentId: string;
}

interface OptionItem {
  label: string;
  value: string;
}

const familyOptions = ref<OptionItem[]>([]);
const zibeiOptions = ref<OptionItem[]>([
  { label: "字辈A", value: "A" },
  { label: "字辈B", value: "B" },
]);
const genderOptions = ref<OptionItem[]>([
  { label: "男", value: "1" },
  { label: "女", value: "0" },
]);
const aliveOptions = ref<OptionItem[]>([
  { label: "在世", value: "1" },
  { label: "已故", value: "0" },
]);

const eraOptions = ref<OptionItem[]>([
  { label: "公元前", value: "BC" },
  { label: "公元", value: "AD" },
]);

const formData = ref<FormData>({
  familyId: "",
  firstName: "",
  lastName: "",
  nickname: "",
  genation: "",
  gender: "",
  alive: "1", // 默认在世
  photoUrl: "",
  occupation: "",
  birthPlace: "",
  address: "",
  birthDate: "",
  deathDate: "",
  birthEra: "AD", // 默认公元后
  deathEra: "AD", // 默认公元后
  biography: "",
  parentId: "",
});

// 错误信息管理
const errors = ref<Record<string, string>>({});

onLoad(async (options) => {
  if (options?.parentId) {
    formData.value.parentId = options.parentId;
  }
  await getFamilyList();
});

// 获取家谱列表
async function getFamilyList() {
  try {
    const res = await FamilyAPI.getMyDetail({ familyId: "", familyName: "" });
    const list = (res as any).list || [];
    if (list.length > 0) {
      familyOptions.value = list.map((item: any) => ({
        label: item.familyName,
        value: String(item.id),
      }));
      // 默认选中第一个家族
      if (!formData.value.familyId) {
        formData.value.familyId = familyOptions.value[0].value;
      }
    }
  } catch (error) {
    console.error("获取家族列表失败:", error);
  }
}

function getFamilyLabel(val: string): string | undefined {
  return (familyOptions.value || []).find((i) => i.value === val)?.label;
}

function getZibeiLabel(val: string): string | undefined {
  return (zibeiOptions.value || []).find((i) => i.value === val)?.label;
}

function getGenderLabel(val: string): string | undefined {
  return (genderOptions.value || []).find((i) => i.value === val)?.label;
}

function getAliveLabel(val: string): string | undefined {
  return (aliveOptions.value || []).find((i) => i.value === val)?.label;
}

function getBirthEraLabel(val: string): string | undefined {
  return (eraOptions.value || []).find((i) => i.value === val)?.label;
}

function getDeathEraLabel(val: string): string | undefined {
  return (eraOptions.value || []).find((i) => i.value === val)?.label;
}

function onFamilyChange(e: any) {
  formData.value.familyId = String(familyOptions.value[e.detail.value].value);
}

function onZibeiChange(e: any) {
  formData.value.genation = String(zibeiOptions.value[e.detail.value].value);
}

function onGenderChange(e: any) {
  formData.value.gender = String(genderOptions.value[e.detail.value].value);
}

function onAliveChange(e: any) {
  formData.value.alive = String(aliveOptions.value[e.detail.value].value);
}

function onBirthDateChange(e: any) {
  const dateValue = e.detail.value;
  // 如果选择的是公元前，则在日期前添加负号
  if (formData.value.birthEra === "BC") {
    formData.value.birthDate = "-" + dateValue;
  } else {
    formData.value.birthDate = dateValue;
  }
}

function onDeathDateChange(e: any) {
  const dateValue = e.detail.value;
  // 如果选择的是公元前，则在日期前添加负号
  if (formData.value.deathEra === "BC") {
    formData.value.deathDate = "-" + dateValue;
  } else {
    formData.value.deathDate = dateValue;
  }
}

function onBirthEraChange(e: any) {
  const newEra = String(eraOptions.value[e.detail.value].value);
  formData.value.birthEra = newEra;

  // 如果已有出生日期，需要根据新的时代重新处理日期格式
  if (formData.value.birthDate) {
    const dateValue = formData.value.birthDate.replace(/^-/, ""); // 移除可能存在的负号
    if (newEra === "BC") {
      formData.value.birthDate = "-" + dateValue;
    } else {
      formData.value.birthDate = dateValue;
    }
  }
}

function onDeathEraChange(e: any) {
  const newEra = String(eraOptions.value[e.detail.value].value);
  formData.value.deathEra = newEra;

  // 如果已有死亡日期，需要根据新的时代重新处理日期格式
  if (formData.value.deathDate) {
    const dateValue = formData.value.deathDate.replace(/^-/, ""); // 移除可能存在的负号
    if (newEra === "BC") {
      formData.value.deathDate = "-" + dateValue;
    } else {
      formData.value.deathDate = dateValue;
    }
  }
}

// 获取显示用的出生日期（移除负号用于显示）
function getDisplayBirthDate(): string {
  if (!formData.value.birthDate) return "";
  return formData.value.birthDate.replace(/^-/, "");
}

// 获取显示用的死亡日期（移除负号用于显示）
function getDisplayDeathDate(): string {
  if (!formData.value.deathDate) return "";
  return formData.value.deathDate.replace(/^-/, "");
}

function onSubmit() {
  // 清除之前的错误信息
  errors.value = {};

  // 表单验证
  const validationErrors: Record<string, string> = {};

  // 验证姓
  if (!formData.value.firstName?.trim()) {
    validationErrors.firstName = "请输入姓";
  }

  // 验证名
  if (!formData.value.lastName?.trim()) {
    validationErrors.lastName = "请输入名";
  }

  // 验证性别
  if (!formData.value.gender) {
    validationErrors.gender = "请选择性别";
  }

  // 验证是否在世
  if (!formData.value.alive) {
    validationErrors.alive = "请选择是否在世";
  }

  // 验证头像照片
  if (!formData.value.photoUrl) {
    validationErrors.photoUrl = "请上传头像照片";
  }

  // 验证职业
  if (!formData.value.occupation?.trim()) {
    validationErrors.occupation = "请输入职业";
  }

  // 验证籍贯
  if (!formData.value.birthPlace?.trim()) {
    validationErrors.birthPlace = "请输入籍贯";
  }

  // 验证地址
  if (!formData.value.address?.trim()) {
    validationErrors.address = "请输入地址";
  }

  // 验证出生日期
  if (!formData.value.birthDate) {
    validationErrors.birthDate = "请选择出生日期";
  }

  // 如果有验证错误，显示错误信息并返回
  if (Object.keys(validationErrors).length > 0) {
    errors.value = validationErrors;

    // 构建具体的错误提示信息
    const missingFields = Object.values(validationErrors);
    const errorMessage = missingFields.length > 0 ? missingFields[0] : "请完善必填信息";

    uni.showToast({
      title: errorMessage,
      icon: "none",
      duration: 3000,
    });
    return;
  }

  // 确保日期数据包含正确的负号
  let birthDateToSubmit = formData.value.birthDate;
  let deathDateToSubmit = formData.value.deathDate;

  // 处理出生日期
  if (formData.value.birthDate && formData.value.birthEra === "BC") {
    if (!formData.value.birthDate.startsWith("-")) {
      birthDateToSubmit = "-" + formData.value.birthDate;
    }
  } else if (formData.value.birthDate && formData.value.birthEra === "AD") {
    birthDateToSubmit = formData.value.birthDate.replace(/^-/, "");
  }

  // 处理死亡日期
  if (formData.value.deathDate && formData.value.deathEra === "BC") {
    if (!formData.value.deathDate.startsWith("-")) {
      deathDateToSubmit = "-" + formData.value.deathDate;
    }
  } else if (formData.value.deathDate && formData.value.deathEra === "AD") {
    deathDateToSubmit = formData.value.deathDate.replace(/^-/, "");
  }

  // 创建提交数据，排除 birthEra 和 deathEra 字段
  const { birthEra, deathEra, ...submitDataWithoutEra } = formData.value;
  const submitData = {
    ...submitDataWithoutEra,
    birthDate: birthDateToSubmit,
    deathDate: deathDateToSubmit,
    gender: Number(formData.value.gender),
    alive: Number(formData.value.alive),
    longitude: null,
    latitude: null,
    flag: 0,
    motherId: null,
    type: null,
    personId: null,
  };

  PersonAPI.create(submitData)
    .then(() => {
      uni.showToast({ title: "提交成功", icon: "success" });
      setTimeout(() => {
        uni.navigateTo({
          url: "/pages/genealogy/person/index",
        });
      }, 800);
    })
    .catch((error) => {
      console.error("提交失败:", error);
      uni.showToast({ title: "提交失败", icon: "error" });
    });
}
function onCancel() {
  uni.navigateBack();
}
</script>

<style scoped>
.add-child-page {
  margin: 20rpx auto;
  background: #fff;
  border-radius: 16px;
  padding: 28px 18px 18px 18px;
  box-shadow: 0 2px 16px #eee;
}

.form-item {
  margin-bottom: 18px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f2f2f2;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-item text {
  font-weight: 600;
  font-size: 16px;
  color: #222;
  margin-bottom: 2px;
}
.required::before {
  content: "* ";
  color: #ff4d4f;
}

input,
textarea,
.picker {
  width: 95%;
  padding: 8px 10px;
  border: 1px solid #e5e6eb;
  border-radius: 8px;
  font-size: 15px;
  color: #333;
  background: #fafbfc;
  transition: border 0.2s;
}

input:focus,
textarea:focus {
  border: 1.5px solid #165dff;
  background: #fff;
}

.picker {
  display: flex;
  align-items: center;
  color: #666;
  background: #fafbfc;
  cursor: pointer;
}

::placeholder {
  color: #bbb;
  font-size: 14px;
}

.form-actions {
  display: flex;
  gap: 16px;
  margin-top: 28px;
}

.form-actions button {
  flex: 1;
  height: 42px;
  border-radius: 22px;
  font-size: 16px;
  font-weight: 600;
}

.form-actions button[type="primary"] {
  background: #3c9cff;
  color: #fff;
  border: none;
}

/* .form-actions button:not([type="primary"]) {
  background: #f5f5f5;
  color: #666;
  border: none;
} */

/* 头像上传样式优化（可选） */
.uni-file-picker {
  margin-top: 6px;
  border-radius: 8px;
  background: #fafbfc;
  border: 1px solid #e5e6eb;
}

.avatar-uploader {
  margin-top: 6px;
}

.avatar-uploader .uni-file-picker__container {
  display: flex;
  align-items: center;
}

.avatar-uploader .uni-file-picker__image {
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid #e5e6eb;
  width: 80px;
  height: 80px;
}

.date-row {
  display: flex;
  gap: 10px;
  align-items: center;
}

.era-picker {
  width: 80px;
  padding: 8px 10px;
  border: 1px solid #e5e6eb;
  border-radius: 8px;
  font-size: 15px;
  color: #333;
  background: #fafbfc;
  text-align: center;
}

.date-picker {
  flex: 1;
  padding: 8px 10px;
  border: 1px solid #e5e6eb;
  border-radius: 8px;
  font-size: 15px;
  color: #333;
  background: #fafbfc;
}
</style>
